package org.openarchitectureware.recipe2.findbugs;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.Detector2;
import edu.umd.cs.findbugs.IClassAnnotation;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.ann.AnnotationFactory;
import edu.umd.cs.findbugs.ba.AnalysisContext;

public class FindBugsUtil {
	private static void addParameters(PredefInstance predefInstance, BugInstance bugInstance) {
		for (Map.Entry<String, String> param : predefInstance.getParameters().entrySet()) {
			bugInstance.addString(param.getValue());
		}
		String message = predefInstance.getMessage();
		if (message == null) {
			message = "";
		}
		bugInstance.addString(message);
	}

	public static BugInstance createBugInstance(Detector detector, String bugPattern, PredefInstance predefInstance, String primaryClass, int priority) {
		BugInstance bugInstance = new BugInstance(detector, bugPattern, priority);
		configureBugInstance(detector, predefInstance, primaryClass, bugInstance);
		return bugInstance;
	}
	public static BugInstance createBugInstance(Detector2 detector, String bugPattern, PredefInstance predefInstance, String primaryClass, int priority) {
		BugInstance bugInstance = new BugInstance(detector, bugPattern, priority);
		configureBugInstance(detector, predefInstance, primaryClass, bugInstance);
		return bugInstance;
	}

	private static void configureBugInstance(Object detector, PredefInstance predefInstance, String primaryClass, BugInstance bugInstance) {
		addParameters(predefInstance, bugInstance);
		addPrimaryClassAnnotation(detector, primaryClass, bugInstance);
	}

	private static void addPrimaryClassAnnotation(Object detector, String primaryClass, BugInstance bugInstance) {
		IClassAnnotation classAnnotation = AnnotationFactory.createClass(primaryClass);
		bugInstance.add(classAnnotation);
	}

	public static List<PredefInstance> loadPredefInstances(Object context, String predefName, BugReporter bugReporter) {
		try {
			return XMLPredefInstancesReader.getPredefInstances(predefName, context);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private FindBugsUtil() {}

	public static void configureMissingClassDetails(String javaClassName, BugInstance bugInstance) {
		AnalysisContext.currentAnalysisContext().getSubtypes2().addApplicationClass(new NonExistingClass(javaClassName));
		bugInstance.add(SourceLineAnnotation.createReallyUnknown(javaClassName));
	}
}
